import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.*;

import javax.swing.JFrame;

public class InputHandler implements MouseListener, MouseMotionListener,
		MouseWheelListener, KeyListener {

	private JFrame frame;
	private World world;
	private Robot robot;

	public InputHandler(JFrame f, World w) {
		world = w;
		frame = f;
		try {
			robot = new Robot();
		} catch (AWTException e) {
			// TODO warn
		}
	}

	public void attach(java.awt.Component component) {
		component.addMouseListener(this);
		component.addMouseMotionListener(this);
		component.addMouseWheelListener(this);
		component.addKeyListener(this);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseMoved(MouseEvent e) {
		int rX = frame.getLocationOnScreen().x + frame.getWidth() / 2;
		int rY = frame.getLocationOnScreen().y + frame.getHeight() / 2;
		world.p.setViewRotx((double) (world.p.getVeiwRotx())
				+ (double) (e.getXOnScreen() - rX) / 10);
		world.p.setViewRoty((double) (world.p.getVeiwRoty())
				- (double) (e.getYOnScreen() - rY) / 10);

		// Move mouse to the center of the window
		robot.mouseMove(rX, rY);
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (e.getKeyChar() == 'w') {
			world.p.incrz = 0;
		}
		if (e.getKeyChar() == 's') {
			world.p.incrz = 0;
		}
		if (e.getKeyChar() == 'a') {
			world.p.incrx = 0;
		}
		if (e.getKeyChar() == 'd') {
			world.p.incrx = 0;
		}
	}

	@Override
	public void keyPressed(KeyEvent e) {

		if (e.getKeyChar() == 'f') {
			if (world.p.fly == 0)
				world.p.fly = 1;
			else
				world.p.fly = 0;
		}

		if (e.getKeyChar() == 'w') {
			world.p.incrz = world.p.moveSpeed;
		}
		if (e.getKeyChar() == 's') {
			world.p.incrz = -world.p.moveSpeed;
		}
		if (e.getKeyChar() == 'a') {
			world.p.incrx = -world.p.moveSpeed;
		}
		if (e.getKeyChar() == 'd') {
			world.p.incrx = world.p.moveSpeed;
		}
		if (e.getKeyCode() == KeyEvent.VK_SPACE) {
			world.p.jump = 1;
		}
		if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
			System.exit(0);
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseWheelMoved(MouseWheelEvent arg0) {
		// TODO Auto-generated method stub

	}

}
